package net.towee.server.authentication.impl;

import javax.inject.Inject;

import net.towee.server.authentication.SessionAuthManager;
import net.towee.server.persistence.AccountStore;
import net.towee.server.sio.server.SocketIOServlet;
import net.towee.shared.exceptions.PersistenceException;

import org.eclipse.jetty.server.session.HashSessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This extended hash session manager may contain some logic
 * when any session deleting.  
 * @author c58
 *
 */
public class SessionHttpManagerImpl extends HashSessionManager {
	private static final Logger LOG = LoggerFactory.getLogger(SessionHttpManagerImpl.class);
	
	public static SessionHttpManagerImpl INSTANCE;
	
	// Injected
	private final AccountStore accStore;
	private final SessionAuthManager authManager;

	@Inject
	public SessionHttpManagerImpl(AccountStore accStore, SessionAuthManager authManager){
		this.accStore = accStore;
		this.authManager = authManager;
		
		// Inactive time
		setMaxInactiveInterval( SocketIOServlet.CLOSE_TIMEOUT*4 );
		
		// FIXME: Set in static holder ( baaad :( )
		INSTANCE = this;
	}
	
	/**
	 * This method remove session and update last user activity
	 * date.
	 */
	@Override
	protected boolean removeSession(String clusterId) {		
		// Get user id from given session
		String userId = authManager.getLoggedInUser( authManager.getSessionFromToken(clusterId), null );
		
		LOG.info("User session removed: session("+clusterId+"); userId("+userId+")  ");
		
		// Update last activity date
		accStore.updateLastSessionDate(userId);
		accStore.setOnlineState(userId, false);
		
		// Remove session
		return super.removeSession(clusterId);
	}
}
